#include "sendaudio.h"

SendAudio::SendAudio(QObject *parent)
    : QThread(parent)
{
    udpSocket = new QUdpSocket(this);
}

SendAudio::~SendAudio(){
    delete udpSocket;
    delete audioIn;
    delete inputDevice;
}


void SendAudio::init(QString ip, int srcP, int dstP, int quality, QAudioDeviceInfo devInfo)
{
    srcPort=srcP;
    dstPort=dstP;
    udpSocket->bind(QHostAddress::Any, srcPort);

    destaddr.setAddress(ip);//目的地址

    setFormat(quality);
    if (!devInfo.isFormatSupported(format))
    {
       qWarning()<<"default format not supported try to use nearest";
       format = devInfo.nearestFormat(format);
    }
    audioIn = new QAudioInput(devInfo, format, this);
}

void SendAudio::mystart(int delay)
{
    inputDevice = audioIn->start();
//    connect(inputDevice,SIGNAL(readyRead()),this,SLOT(onReadyRead()));

    m_timer = new QTimer(this);
    m_timer->setSingleShot(false);
    m_timer->start(delay);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(onReadyRead()));
}

void SendAudio::mystop(){
    audioIn->stop();
    m_timer->stop();
}

void SendAudio::onReadyRead(){

    char data[SENDBYTES];
    memset(data,0,SENDBYTES);
    int len = inputDevice -> read(data,SENDBYTES);
    int num = udpSocket -> writeDatagram(data, len,destaddr,dstPort);

//    qDebug() <<"sendBytes:"<<num<<endl;
}


void SendAudio::setFormat(int quality)
{
    format.setSampleSize(16);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);

    switch(quality){
        case 0:
            format.setSampleRate(48000);
            format.setChannelCount(2);
            break;
        case 1:
            format.setSampleRate(44100);
            format.setChannelCount(2);
            break;
        case 2:
            format.setSampleRate(16000);
            format.setChannelCount(2);
            break;
        case 3:
            format.setSampleRate(8000);
            format.setChannelCount(2);
            break;
        case 4:
            format.setSampleRate(48000);
            format.setChannelCount(1);
            break;
        case 5:
            format.setSampleRate(44100);
            format.setChannelCount(1);
            break;
        case 6:
            format.setSampleRate(16000);
            format.setChannelCount(1);
            break;
        case 7:
            format.setSampleRate(8000);
            format.setChannelCount(1);
            break;
        default:
            format.setSampleRate(8000);
            format.setChannelCount(1);
    }
}


